import { fileDelete, sceneRecordSubmit } from '../../api/user'
import { apiAddress } from '../../utils/config'
import { getToken } from '../../utils/permission'
import { debounce } from '../../utils/util'

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    form: {
      list_pic: [],
      title: '',
      address: '',
      defect: '',
      opinion: '',
      list_picRules: [
        {
          required: true,
          message: '请选择图片',
          trigger: 'blur',
          type: 'array'
        }
      ],
      addressRules: {
        required: true,
        message: '请输入位置',
        trigger: 'blur'
      },
      defectRules: {
        required: true,
        message: '请输入缺点',
        trigger: 'blur'
      }
    },
    baseUrl: apiAddress,
    formData: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.lin.initValidateForm(this)

    this.setData({
      img: options.tempFilePath
    })
  },

  _checkPic: function () {
    wx.previewImage({
      current: this.data.img,
      urls: [this.data.img]
    })
  },

  _submit: debounce(function (event) {
    const { detail } = event
    if (!detail.isValidate) return
    wx.showLoading({
      title: '添加中，请稍后',
      mask: true
    })
    sceneRecordSubmit({
      list_pic: detail.values.formImg.map((d) =>
        d.replace(this.data.baseUrl + '/storage/', '')
      ),
      address: detail.values.formAddress,
      defect: detail.values.formDefect ? detail.values.formDefect : undefined,
      opinion: this.data.form.opinion
        ? this.data.form.opinion.replace(
            this.data.baseUrl + '/storage/',
            '${baseUrl}'
          )
        : undefined
    })
      .then((res) => {
        wx.showModal({
          title: '提交成功，请等待审核',
          showCancel: false,
          success: () => {
            wx.navigateBack({
              delta: 1,
              success: () => {
                app.event.emit('listChanged')
              }
            })
          }
        })
      })
      .finally(() => {
        wx.hideLoading()
      })
  }, 300),

  _onChangeTap: function (event) {
    const { detail } = event
    detail.current.forEach((filePath) => {
      wx.uploadFile({
        url: apiAddress + '/api/user/fileUpload',
        filePath: filePath,
        name: 'file',
        header: {
          Authorization: getToken()
        },
        success: (res) => {
          const data = JSON.parse(res.data)
          if (data.code == 200) {
            this.setData({
              ['form.list_pic']: [
                ...this.data.form.list_pic,
                this.data.baseUrl + '/storage/' + data.data
              ]
            })
          } else {
            wx.showModal({
              title: data.msg || '上传失败',
              showCancel: false
            })
            this.setData({
              ['form.list_pic']: [...this.data.form.list_pic]
            })
          }
        },
        fail: () => {
          wx.showModal({
            title: '上传失败',
            showCancel: false
          })
          this.setData({
            ['form.list_pic']: [...this.data.form.list_pic]
          })
        }
      })
    })
  },

  _onInputtingDesc: function (e) {
    const { html } = e.detail
    this.setData({
      ['form.opinion']: html
    })
  },

  _onRemoveImg: function (e) {
    const { current, index } = e.detail
    const { list_pic } = this.data.form
    list_pic.splice(index, 1)
    this.setData({
      ['form.list_pic']: list_pic
    })
    fileDelete({
      filePath: current.replace(this.data.baseUrl + '/storage/', '')
    }).catch(() => {})
  }
})
